
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include <memory>
#include <signal.h>
#include "Daemon.hpp"

using namespace ns_tcpserver;
using namespace ns_protocal;

static void Usage(const std::string &process)
{
    std::cout << "\nUsage: " << process << " port\n"
              << std::endl;
}

static Response calculatorHelper(const Request &req)
{
    Response resp(0, 0,req.x_,req.y_,req.op_);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if(0==req.y_)
            resp. code_ = 1;
        else
            resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if(0==req.y_)
            resp. code_ = 2;
        else
            resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}

void calculator(int sock)
{
    std::string inbuffer;
    while (true)
    {
        bool res = Recv(sock,&inbuffer);
        if(!res)
        {
            break;
        }
        std::string package = Decode(inbuffer);
        if(package.empty())
        {
            continue;
        }
        logMessage(NORMAL,"%s",package.c_str());
        
        Request req;
        req.Deserialized(package);

        Response resp = calculatorHelper(req);
        std::string respStr = resp.Serialiaze();
        respStr = Encode(respStr);
        Send(sock,respStr);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    MyDaemon();

    std::unique_ptr<TcpServer> server(new TcpServer(atoi(argv[1])));
    server->BindServer(calculator);
    server->Start();

    // Request req(123, 456, '+');
    // std::string s = req.Serialiaze();
    // std::cout << s << std::endl;

    return 0;
}